package servlet;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

// 标注Servlet的URL映射为/download.do
@WebServlet("/download.do")
public class DownServlet extends HttpServlet {

    private static final long serialVersionUID = 3L;

    // 处理GET请求，转发给doPost方法处理
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    // 处理POST请求
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        // 设置请求和响应的字符编码为UTF-8
//        request.setCharacterEncoding("utf-8");
//        response.setCharacterEncoding("utf-8");

        // 获取请求参数中的文件名
        String fileName = request.getParameter("f");

        // 构建文件对象
        File file = new File("C:/程序设计/JavaWeb/press-release-system/web/resources/newsimg/"+fileName);

        // 判断文件是否存在
        if (file.exists()) {
            // 设置响应内容类型为二进制流
            response.setContentType("application/octet-stream");
            // 设置响应头，指示浏览器下载文件并指定文件名
            response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8"));
            // 创建文件输入流和响应输出流
            InputStream is = new FileInputStream(file);
            OutputStream os = response.getOutputStream();
            byte[] arr = new byte[1024];
            int len = 0;
            // 读取文件并写入响应输出流
            while ((len = is.read(arr)) != -1) {
                os.write(arr, 0, len);
            }
            // 关闭输入流和输出流
            is.close();
            os.close();
        } else {
            // 如果文件不存在，返回提示信息
            response.setContentType("text/html; charset=UTF-8");
            response.getWriter().write("文件不存在！");
        }
    }
}
